<template>
<section>
    <el-col :sm="24" :lg="16">
        <div class="grid-content bg-purple" :style="{backgroundColor:titleColor}">
            <div class="dev-title">设备转移</div>
        </div>     
        <div class="col-bg clearfix">
            <el-form ref="form"  :model="form" label-width="100px" @submit.prevent="onSubmit"
                style="margin:20px;width:80%;">
                <el-form-item v-if="usertype==2" label="组织名字" >
                    <el-select v-model="companyId" placeholder="选择组织" @change="userget()">

                        <el-option v-for="(item,index) in userlist" :key="item.companyId" :label="item.name"
                            :value="item.companyId"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="设备">
                    <el-select multiple collapse-tags v-model="form.deviceId" filterable placeholder="设备">
                        <el-option v-for="(item,index) in devicelist" :key="item.deviceId"
                            :label="item.name+'('+item.deviceSn+')'" :value="item.deviceId"></el-option>
                    </el-select>
                    <el-popover width="400" trigger="click" placement="right"  popper-class="attributes">
                        <el-row :gutter="10">
                            <el-col :span="9"><el-input placeholder="设备名称" v-model="filter.name" @keyup.enter.native="userget()"></el-input></el-col>
                            <el-col :span="10"><el-input placeholder="网关SN" v-model="filter.deviceSn" @keyup.enter.native="userget()"></el-input></el-col>
                            <el-col :span="4"><el-button size="medium" @click="userget()">筛选</el-button></el-col>
                        </el-row>
                        
                        <i title="筛选" slot="reference" class="el-icon-search" style="color:#409EFF;font-size:20px;cursor: pointer;"></i>
                    </el-popover>
                    <div style="font-size: 12px;color: #a5a5a5;" v-if="form.deviceId.length>0">已选中 {{form.deviceId.length}} 个设备</div>
                </el-form-item>
                <el-form-item label="转到的组织" prop="phone">
              
                    <el-select  v-model="form.toCompanyId" filterable placeholder="选择组织">

                   
                        <el-option v-for="(item,index) in userlist"  :label="item.name"
                            :value="item.companyId"></el-option>
                    </el-select>
                </el-form-item>
              
                <el-form-item>
                    <el-button :type="buttonColor" @click.native="onSubmit" :loading="editLoading">提交</el-button>
                </el-form-item>
            </el-form>
        </div>
    </el-col>
    <el-col :sm="24" :lg="16">
        <div class="grid-content bg-purple" :style="{backgroundColor:titleColor}">
            <div class="dev-title">txt文本批量转移</div>
        </div>     
        <div class="col-bg clearfix">
            <el-form ref="form"  :model="form" label-width="100px" @submit.prevent="onSubmit"
                style="margin:20px;width:80%;">
                <el-form-item>
                    <el-upload class="upload-demo" action="https://jsonplaceholder.typicode.com/posts/" ref="upload"
                        accept=".txt" :on-change="upload" :show-file-list="false" :auto-upload="false" style="display: inline;">
                        <el-button style="" size="mini" :type="buttonColor">选择txt文件</el-button>
                    </el-upload>
                </el-form-item>
                <el-form-item>
                    <div style="font-size: 12px;color: #a5a5a5;" v-if="deviceSnList.length>0">已选中 {{deviceSnList.length}} 个设备</div>
                </el-form-item>
                <el-form-item label="转到的组织" prop="phone">
                    <el-select  v-model="toBatchCompanyId" filterable placeholder="选择组织">
                        <el-option v-for="(item,index) in userlist"  :label="item.name"
                            :value="item.companyId"></el-option>
                    </el-select>
                </el-form-item>
              
                <el-form-item>
                    <el-button :type="buttonColor" @click.native="batchSubmit">提交</el-button>
                </el-form-item>
            </el-form>
        </div>
    </el-col>
</section>
</template>

<script>
    import {
        device_query_mini,
        user_querycompany,
        device_change_user,
    } from '../../api/api';
    import {
        batch_transfer_device
    }from '../../api/devices/transfer'
    import XLSX from 'xlsx'
    export default {
        data() {
            return {
                userId:'',
                usertype:'',
                companyId: '',
                userlist: '',
                editLoading:false,
                // firmlist: '',
                devicelist: '',
                filter:{
                    name:'',
                    deviceSn:''
                },
                form: {
                    deviceId: [],
                    // toUserId: ''
                    toCompanyId:''
                },
                deviceSnList:[],//批量转移的Sn
                toBatchCompanyId:"",//批量转移目标组织的id
            }
        },
        computed:{
            buttonColor(){
                return this.$store.state.buttonColor
            },
            titleColor(){
                return this.$store.state.titleColor
            },
            dialogTitleColor(){
                return this.$store.state.dialogTitleColor
            },
        },
        methods: {
            //批量转移提交后执行
            batchSubmit(){
                let para = {
                    deviceSnList: this.deviceSnList,
                    toCompanyId: this.toBatchCompanyId
                }
                console.log(para)
                if(para.deviceSnList.length==0){
                    this.$message({
                        message: '请选择.txt文本文件',
                        type: 'warning'
                    });
                    return false
                }
                if(!para.toCompanyId){
                    this.$message({
                        message: '请选择转移到的组织',
                        type: 'warning'
                    });
                    return false
                }
                this.$confirm('确认提交吗？', '提示', {}).then(() => {
                    batch_transfer_device(para).then(res => {
                        console.log(res)
                        this.$message({
                            message: '转移成功',
                            type: 'success'
                        });
                        this.deviceSnList = []
                        this.toBatchCompanyId = ""
                    })
                }) 
            },
            //excel批量上传
            upload(file, fileList) {
                console.log("file", file);
                console.log("fileList", fileList);
                let that = this
                let files = {
                    0: file.raw
                }
                var reader = new FileReader();
                reader.onload = function () {
                    if (reader.result) {
                        //打印文件内容
                        let list = reader.result.split("\r\n")
                        // console.log(reader.result);
                        console.log(list);
                        that.deviceSnList = list
                    }
                };
                reader.readAsText(file.raw);
            },
            userget() {
                
                this.form={
                    deviceId: [],
                    // toUserId: ''
                    toCompanyId:''
                };
                let para = {
                    pageNo: 1,
                    pageSize: 9999,
                    type: 0, 
                    authType: 0,
                    companyId: this.companyId

                }
                let para1 = {
                    pageNo: 1,
                    pageSize: 9999,
                    companyId: this.companyId,
                    name: this.filter.name,
                    deviceSn: this.filter.deviceSn,
                    miniLev:2

                }
                // user_query(para).then((res) => {
                //     console.log(res)
                //     this.begCode(res.code, res.message);
                //     this.firmlist = res.data.list;
                //     if(this.usertype!=2){
                //         let item1={
                //             userName:'当前账户',
                //             userId:this.userId
                //         }
                //         this.firmlist.splice(0, 0, item1);
                //     }
                    


                // });
                device_query_mini(para1).then((res) => {
                    this.begCode(res.code, res.message);
                    this.devicelist = res.data.list;
                });
            },
            getUsers() {
                let parauser = {
                    pageNo: 1,
                    pageSize: 9999,
                }
                
                let para = {
                    pageNo: 1,
                    pageSize: 9999,
                    type: 1
                }
                user_querycompany(para).then((res) => {
                    this.begCode(res.code, res.message);
                    this.userlist = res.data.list;
                    // console.log(this.userlist)
                });
                // if(this.usertype!=2){
                //     this.companyId=JSON.parse(sessionStorage.getItem('user')).companyId;
                //     console.log(this.companyId)
                //     this.userget();
                // }
                this.userget()
            },
            onSubmit() {
                if (!this.form.deviceId) {
                    this.$message({
                        message: '请选择要转移的设备',
                        type: 'warning'
                    });
                    return false;
                }
                if (!this.form.toCompanyId) {
                    this.$message({
                        message: '请选择要转到的组织',
                        type: 'warning'
                    });
                    return false;
                }
                if(this.form.toCompanyId == this.companyId){
                    this.$message({
                        message: '请选择正确转到的组织',
                        type: 'warning'
                    });
                    return false;
                }
                this.$confirm('确认提交吗？', '提示', {}).then(() => {
                    for(let i in this.form.deviceId){
                        let para = {
                            deviceId: this.form.deviceId[i],
                            toCompanyId: this.form.toCompanyId
                        }
                        console.log(para)
                        device_change_user(para).then((res) => {
                            if (res.code == 0) {
                                this.editLoading = false;
                                this.$message({
                                    message: '提交成功',
                                    type: 'success'
                                });
                                
                                this.userget();
                            } else if(res.code == 600){
                                this.$message({
                                    message: '设备已在该组织内',
                                    type: 'warning'
                                });
                            }else{
                                this.begCode(res.code, res.message);
                            }
                        });
                    }
                    // this.editLoading = true;
                    // let para = Object.assign({}, this.form);
                    // console.log(para)
                    // device_change_user(para).then((res) => {
                    //     if (res.code == 0) {
                    //         this.editLoading = false;
                    //         this.$message({
                    //             message: '提交成功',
                    //             type: 'success'
                    //         });
                            
                    //         this.userget();
                    //     } else {
                    //         this.begCode(res.code, res.message);
                    //     }
                    // });
                });
            }
        },
        mounted() {
            this.usertype = JSON.parse(sessionStorage.getItem('user')).type;
            // if(this.usertype!=2){

                this.userId=JSON.parse(sessionStorage.getItem('user')).userId;
            // }
            this.getUsers();
        }
    }
</script>
<style>
    .avatar-uploader .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }

    .avatar-uploader .el-upload:hover {
        border-color: #409EFF;
    }

    .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        line-height: 178px;
        text-align: center;
    }

    .avatar {
        width: 178px;
        height: 178px;
        display: block;
    }
</style>